<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\AdminUser;
use think\Validate;
use app\admin\controller\Main;
class Admins extends Main
{
    public function adminList()
    {
        $name = input('post.name');
        if(empty($name)){
            $data = AdminUser::where(true)->paginate(4);
        }else{
             $data = AdminUser::where('admin_username','like',"%$name%")->paginate(4);
        }
        $count = AdminUser::count();
        $this->assign('list',$data);
        $this->assign('count',$count);
        return $this->fetch('admin/admin-list');
    }

    //显示添加
    public function addAdmin()
    {
        $data = Db::name('role')->field('role_id,role_name')->select();
        // dump($data);die;
        $this->assign('list',$data);
    	return $this->fetch('admin/admin-add');
    }
    public function add()
    {
        $data = input('post.');
        $roles = $data['roles'];
        $validate = new Validate([
                'admin_username'  => 'require|min:1',
                'admin_tel'=>['regex'=>'/^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/']
        ]);

        if (!$validate->check($data)) {
            $arr = ['status'=>0,'message'=>$validate->getError()];
        }else{
            $username = Db::name('admin_user')->where(['admin_username'=>$data['admin_username']])->find();
            if($username){
                 $arr = ['status'=>0,'message'=>'管理员名字存在'];
            }else{
                $admin['admin_username'] = $data['admin_username'];
                $admin['admin_tel'] = $data['admin_tel'];
                $admin['admin_pwd'] = md5($data['admin_pwd']);
                $admin['admin_regtime'] = time();
                $lastInsertId = Db::name('admin_user')->insertGetId($admin);
                if($lastInsertId){
                    foreach($roles as $v){
                        Db::name('admin_role')->insert(['aid'=>$lastInsertId,'rid'=>$v]);
                    }
                    $arr = ['status'=>0,'message'=>'添加成功'];
                }else{
                    $arr = ['status'=>0,'message'=>'添加失败'];
                }
            }
        }

        if ($arr['status'] == 0) {
            return $this->error($arr['message']);
        } else {
            return $this->success($arr['message'],url('admin/Admins/adminList'));
        }

    }


    //删除管理员
    public function delAdmin($id)
    {
        $result = Db::name('admin_user')->delete($id);
         if ($result > 0) {
            $res = Db::name('admin_role')->where('aid',$id)->delete($id);
            $info['status'] = true;
            $info['id'] = $id;
            $info['info'] = 'ID为: ' . $id . '的管理员删除成功!';
        } else {
            $info['status'] = false;
            $info['id'] = $id;
            $info['info'] = 'ID为: ' . $id . '的管理员删除失败!';
        }

        return json($info);
    }
    //编辑管理员信息
    public function editAdmin()
    {
    	
    }

    //显示角色详情
    public function roleMessage($id)
    {
        $data = DB::name('admin_role')->field('rid')->where('aid',$id)->select();
        if(!empty($data)){
            foreach($data as $v){
                $ids[] = $v['rid'];
             }
        }else{
            $ids[] = 'hello';
        }
       
        $rolemessage = DB::name('role')->field(true)->where('role_id','in',$ids)->select();
        // dump($rolemessage);
        $this->assign('list',$rolemessage);
        return $this->fetch('role/role-message');
    }

    //修改禁用和启用

    public function changeStatus1($id)
    {
        AdminUser::where('admin_id', $id)
                ->update(['admin_status' => '2']);
        return $id;
    }

    public function changeStatus2($id)
    {
        AdminUser::where('admin_id', $id)
                ->update(['admin_status' => '1']);
        return $id;
    }

    public function editlist($id)
    {
        $data = Db::name('admin_user')->find($id);

        $role = Db::name('admin_role')->field('rid')->where('aid',$id)->select();
        if(!empty($role)){
            foreach($role as $v){
                $newarr[] =  $v['rid'];
            }

        }else{
            $newarr = ['hello'];
        }

        foreach($role as $v){
            $newrole[] = $v['rid'];
        }
        //根据id查询角色信息
        $rows = Db::name('role')->field('role_id,role_name')->select();
        
        // dump($newarr);die;

        $this->assign('list',$rows);
        $this->assign('data',$data);
        $this->assign('rows',$newarr);
        return $this->fetch('admin/admin-edit');
    }

    public function adminEdit($id)
    {
        $data = input('post.');
        $admin['admin_username'] = $data['username'];
        $admin['admin_tel'] = $data['phone'];
        $i=0;
        $ids = $data['id']; 
        foreach($ids as $v){
            $idsupdate[$i]['aid'] = $id;
            $idsupdate[$i]['rid'] = $v;
            $i++;
        }
        // dump($idsupdate);die;
        try{
            Db::name('admin_user')->where('admin_id',$id)->update($admin);
            Db::name('admin_role')->where('aid',$id)->delete();
            DB::name('admin_role')->insertAll($idsupdate);
            // 提交事务
            Db::commit();    
            $error = ['status'=>1,'message'=>'修改成功'];
        } catch (\Exception $e) {
            // 回滚事务
            $error = ['status'=>0,'message'=>'修改失败'];
            Db::rollback();
        }

        if ($error['status'] == 0) {
            // return '<div style="font-size:50px;color:red;height:300px;width:300px;margin:100px auto;">'.$error['message'].'</div>';
            return $this->error($error['message']);
        } else {
            return $this->success($error['message']);
            // return '<div style="font-size:50px;color:red;height:300px;width:300px;margin:100px auto;">'.$error['message'].'</div>';
        }
    }
}
